package com.bgt.springboot.first.controller;

/**
 * Created by baiguantao on 2017/4/21.
 */

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * 自定义事务管理方式
 *
 * 使用示例
 *
 @Transactional(value="transactionManager1")
 public void save() {
 doSave();
 }
 */
@Configuration
public class Transaction  implements TransactionManagementConfigurer {
    @Resource(name="transactionManager")
    private PlatformTransactionManager txManager2;
    @Bean(name = "transactionManager1")
    public PlatformTransactionManager transactionManager1(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager2(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean(name = "transactionDManager")
    public PlatformTransactionManager transactionManager3(DruidDataSource dataSource) {
        System.out.println("阿里----");
        return new DataSourceTransactionManager(dataSource);
    }
    // 实现接口 TransactionManagementConfigurer 方法，其返回值代表在拥有多个事务管理器的情况下默认使用的事务管理器
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager2;
    }
}
